package com.wt.demo;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description
 * @author: wangtao
 * @date:10:17 2019/6/17
 * @email:386427665@qq.com
 */
public class ThreadCyclicBarrier {

    public static class Soldier implements Runnable {
        private CyclicBarrier cyclic;
        private String soldierName;

        public Soldier(CyclicBarrier cyclic, String soldierName) {
            this.cyclic = cyclic;
            this.soldierName = soldierName;
        }

        @Override
        public void run() {
            try {
                cyclic.await();
                doWork();
                cyclic.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }

        private void doWork() {
            try {
                Thread.sleep(Integer.parseInt(soldierName.substring(soldierName.length() - 1)) * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(soldierName + "：任务完成");
        }
    }

    public static class BarrierRun implements Runnable {
        boolean flag;
        Integer n;
        Object b = new Object();

        public BarrierRun(boolean flag, Integer n) {
            this.flag = flag;
            this.n = n;
        }

        @Override
        public void run() {
            synchronized (b) {
                if (flag) {
                    System.out.println("司令：士兵" + n + "个；任务完成");
                    flag = false;
                } else {
                    System.out.println("司令：士兵" + n + "个；集合完毕");
                    flag = true;
                }
            }
        }
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(5);
        final int n = 5;
        boolean flag = false;
        CyclicBarrier c = new CyclicBarrier(5, new BarrierRun(flag, 5));
        System.out.println("集合队伍");
        for (int i = 0; i < n; i++) {
            System.out.println("士兵" + i + "报到");
            exec.execute(new Soldier(c, "士兵 > " + i));
        }
    }

}
